<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 手机短信接口
 */
class Woocommerce extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $model = null;
    protected $apikey = '';
    protected $secretapikey = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->apikey = 'ck_333c250e1b79cbbe6dc15880a952d098c8bdcf71';
        $this->secretapikey = 'cs_de9373548ab4474ec427f7f34bc9f80522fd65bc';
        $this->model = new \app\admin\model\Feditionorderwoocommerce;
    }


    /**
     * 后台自动获取数据
     * $type 1 拉取所有订单
     * $type 2 实时拉取当下订单
     * $type 3 拉取之前的订单
     */
    public function accounturl_iscustom()
    {
        $type = $this->request->request('type');
        $result = array();
        if(!empty($type)){
            $iscustom = Db::name('fedition_accounturl')
                ->where('iscustom_woocommerce',1)
                ->where('status','normal')
                ->select();
            if($iscustom){
                foreach ($iscustom as $k => $v) {
                    $result[] = $this->orders($v,$type);
                }
            }
        }
        $this->success('操作成功',$result);
    }

    /**
     * orders
     * status
     * pending 待定
    processing 处理中
    on-hold 暂停
    completed 完成
    cancelled 取消
    refunded 退还
    failed 失败
    trash 丢弃
     */
    public function orders($iscustom,$type)
    {
        $per_page = '50';
        $url = $iscustom['url']."/wp-json/wc/v3/orders";
        if($type == 3){
            //拉取之前的订单
            $before_ordershopify = Db::name('fedition_orderwoocommerce')
                ->where('accounturl',$iscustom['id'])
                ->order('ycreated_at asc')
                ->find();
            if($before_ordershopify){
                $created_at_max = $before_ordershopify['ycreated_at'];
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1.'T'.$created_at_max2.'-04:00';
            }
            //拉取之前的订单
            $url = $url.'?before='.$created_at_max;
        }
        if($type == 2){
            $last_ordershopify = Db::name('fedition_orderwoocommerce')
                ->where('accounturl',$iscustom['id'])
                ->order('yupdated_at desc')
                ->find();
            if($last_ordershopify){
                $updated_at_min = $last_ordershopify['yupdated_at'];
            }else{
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2021-07-01T00:00:00-04:00';
            }
            $url = $url.'?after='.$updated_at_min;
        }
        if($type == 1){
            $url = $url.'?per_page='.$per_page;
        }else{
            $url = $url.'&per_page='.$per_page;
        }
        $data = $this->geturl_clicksend($url);
        $result = 0;
        if($data){
            $orders = json_decode($data,true);
            if (!empty($orders['message'])) {
                 return $orders['message'];
            }
            if(is_array($orders) && !empty($orders)){
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as $k => $v) {
                    $row = $this->model->get($v['id']);
                    $arr['id'] = $v['id'];
                    $arr['number'] = $v['number'];
                    //美国时间转北京时间
                    $arr['ycreated_at'] = $v['date_created'];
                    $arr['yupdated_at'] = $v['date_modified'];
                    //店匠显示国内时间
                    $arr['created_at'] = strtotime($v['date_created']);
                    $arr['updated_at'] = strtotime($v['date_modified']);
                    $arr['currency'] = $v['currency'];
                    if (!empty($v['status'])) {
                        $arr['order_status'] = $v['status'];
                    } else {
                        $arr['order_status'] = 'unfulfilled';
                    }
                    $arr['ytotal_price'] = $v['total'];
                    $arr['total_price'] = $v['total'];
                    if ($arr['order_status'] == 'refunded') {
                        $arr['total_price'] = 0;
                    }
                    $arr['accounturl'] = $iscustom['id'];
                    $arr['gateway'] = $v['payment_method'];
                    if($row){
                        if($row['yupdated_at'] !== $arr['yupdated_at']){
                            $result = $row->save($arr);
                        }else{
                            $result = '重复';
                        }
                    }else{
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $result = $this->model->insert($arr);
                    }
                }
            }
        }
        return $result;
    }

    /**
     *同步顾客数据到woocommerce上
     */
    public function update_woocommerce_customers($id = null)
    {
        if (!empty($id)) {
            $this->error('后期再开发');
        }else {
            //对接shopify
            $where = array();
            $return = array();
            $customers_ordershopify = Db::name('fedition_ordershopify')
                ->order('customers_time asc')
                ->where($where)
                ->limit('1')
                ->select();
            if (!empty($customers_ordershopify)) {
                $return['return1'] = $this->customers_ordershopify($customers_ordershopify);
            }
            //对接shoplaza
            $where = array();
            $customers_ordershoplaza = Db::name('fedition_ordershoplaza')
                ->order('customers_time asc')
                ->where($where)
                ->limit('1')
                ->select();
            if (!empty($customers_ordershoplaza)) {
                $return['return2'] = $this->customers_ordershoplaza($customers_ordershoplaza);
            }
            $this->success('操作成功',$return);
        }
    }

    public function customers_ordershopify($customers)
    {
        if (!empty($customers)) {
            foreach ($customers as $t) {
                $accounturl = Db::name('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                if (empty($accounturl['url'])) {
                    //接口查询不到的先不管
                    continue;
                }
                $url = $accounturl['shopifyname'] . "/admin/api/2021-07/orders/" . $t['id'] . ".json";
                $data = $this->geturl_shopify($url, $accounturl['shopifyapikey'], $accounturl['shopifysecretapikey']);
                $data = json_decode($data, true);
                $row = array();
                $row_p = array();
                //如果有woocommerce网站id则修改 没有则添加
                if ($t['customers_id'] > 0) {
//                    连通修改修改
                } else {
                    if (isset($data['order'])) {
                        //开始同步
                        $neworders = array();

                        //先添加商品
                        if (!empty($data['order']['line_items'])) {
                            $line_items = $data['order']['line_items'];
                            if (!empty($line_items)) {
                                foreach ($line_items as $line_item) {
                                    //判断是否有该商品
                                    $fedition_orderproduct = Db::name('fedition_orderproduct')
                                        ->where('product_id', $line_item['product_id'])
                                        ->find();
                                    if (!empty($fedition_orderproduct) && $fedition_orderproduct['customers_status'] == 1) {
                                        $succe['product_id'] = $fedition_orderproduct['customers_id'];
                                        $succe['quantity'] = $line_item['quantity'];
                                        $neworders['line_items'][] = $succe;
                                        //确定已经存到woo里
                                    } else {
                                        $url2 = $accounturl['shopifyname']."/admin/api/2021-07/products/".$line_item['product_id'].".json";
                                        $data2 = $this->geturl_shopify($url2, $accounturl['shopifyapikey'], $accounturl['shopifysecretapikey']);
                                        if($data2) {
                                            $data2 = json_decode($data2, true);
                                            if (!empty($data2['product'])) {
                                                $newproducts = array();
                                                $newproducts['name'] = $data2['product']['title'];
                                                if (isset($data2['product']['variants'][0]['price']) && !empty($data2['product']['variants'][0]['price'])) {
                                                    $newproducts['regular_price'] = $data2['product']['variants'][0]['price'];
                                                }else{
                                                    $newproducts['regular_price'] = 0;
                                                }
                                                $newproducts['description'] = $data2['product']['body_html'];
                                                $newproducts['images'] = array();
                                                if (!empty($data2['product']['images'])) {
                                                    foreach ($data2['product']['images'] as $imagef) {
                                                        if (!empty($imagef['src'])) {
                                                            $newproducts['images'][]['src'] = $imagef['src'];
                                                        }
                                                    }
                                                }
                                                $url_products = 'https://ballclothe.com/wp-json/wc/v3/products';
                                                $return_products = $this->posturl_clicksend($url_products,$newproducts);
                                                $return_products = json_decode($return_products, true);
                                                if (!empty($return_products) && isset($return_products['id']) && !empty($return_products['id'])) {
                                                    $row_p['customers_status'] = 1;
                                                    $row_p['customers_id'] = $return_products['id'];
                                                    $succe['product_id'] = $return_products['id'];
                                                    $succe['quantity'] = $line_item['quantity'];
                                                    $neworders['line_items'][] = $succe;
                                                } else {
                                                    $row_p['customers_status'] = 2;
                                                    if (!empty($return_products['message'])) {
                                                        $row_p['customers_message'] = $return_products['message'];
                                                    }
                                                }
                                            }
                                        }
                                        $row_p['customers_time'] = time();
                                        Db::name('fedition_orderproduct')
                                            ->where('product_id', $line_item['product_id'])
                                            ->update($row_p);
                                    }
                                }
                            }
                        }

                        $neworders['payment_method'] = $data['order']['gateway'];
                        //判读状态
                        $neworders['status'] = $this->neworders_status($data['order'],1);

                        $neworders['billing']['first_name'] = $data['order']['billing_address']['first_name'];
                        $neworders['billing']['last_name'] = $data['order']['billing_address']['last_name'];
                        $neworders['billing']['address_1'] = $data['order']['billing_address']['address1'];
                        $neworders['billing']['address_2'] = $data['order']['billing_address']['address2'];
                        $neworders['billing']['city'] = $data['order']['billing_address']['city'];
                        $neworders['billing']['country'] = $data['order']['billing_address']['country_code'];
                        if (!empty($data['order']['email'])) {
                            $neworders['billing']['email'] = $data['order']['email'];
                        }
                        $neworders['billing']['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "",$data['order']['phone']);

                        $neworders['shipping']['first_name'] = $data['order']['shipping_address']['first_name'];
                        $neworders['shipping']['last_name'] = $data['order']['shipping_address']['last_name'];
                        $neworders['shipping']['address_1'] = $data['order']['shipping_address']['address1'];
                        $neworders['shipping']['address_2'] = $data['order']['shipping_address']['address2'];
                        $neworders['shipping']['city'] = $data['order']['shipping_address']['city'];
                        $neworders['shipping']['country'] = $data['order']['shipping_address']['country_code'];

                        $neworders['shipping_lines'][0]['method_id'] = 'flat_rate';
                        $neworders['shipping_lines'][0]['method_title'] = 'Flat Rate';
                        $neworders['shipping_lines'][0]['total'] = $data['order']['customer']['total_spent'];
                        $url = 'https://ballclothe.com/wp-json/wc/v3/orders';

                        $return_orders = $this->posturl_clicksend($url,$neworders);
                        $return_orders = json_decode($return_orders, true);

                        if (!empty($return_orders) && isset($return_orders['id']) && !empty($return_orders['id'])) {
                            $row['customers_status'] = 1;
                            $row['customers_id'] = $return_orders['id'];
                        } else {
                            $row['customers_status'] = 2;
                            if (!empty($return_orders['message'])) {
                                $row['customers_message'] = $return_orders['message'];
                            }
                        }
                    }
                }

                $row['customers_time'] = time();
                Db::name('fedition_ordershopify')
                    ->where('id', $t['id'])
                    ->update($row);
            }
        }
        return true;
    }

    public function customers_ordershoplaza($customers)
    {
        if (!empty($customers)) {
            foreach ($customers as $t) {
                $accounturl = Db::name('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                if (empty($accounturl['url'])) {
                    //接口查询不到的先不管
                    continue;
                }
                $url = $accounturl['shoplazaname'] . "/openapi/2020-07/orders/" . $t['id'];
                $data = $this->geturl_shoplaza($url,$accounturl['shoplazatoken']);
                $data = json_decode($data, true);
                $row = array();
                $row_p = array();
                //如果有woocommerce网站id则修改 没有则添加
                if ($t['customers_id'] > 0) {
//                    连通修改修改
                } else {
                    if (!empty($data['error'])) {
                        $row['customers_message'] = $data['error'];
                    }
                    if (isset($data['order'])) {
                        //开始同步
                        $neworders = array();

                        //先添加商品
                        if (!empty($data['order']['line_items'])) {
                            $line_items = $data['order']['line_items'];
                            if (!empty($line_items)) {
                                foreach ($line_items as $line_item) {
                                    //判断是否有该商品
                                    $fedition_orderproduct = Db::name('fedition_orderproductp')
                                        ->where('product_id', $line_item['product_id'])
                                        ->find();
                                    if (!empty($fedition_orderproduct) && $fedition_orderproduct['customers_status'] == 1) {
                                        $succe['product_id'] = $fedition_orderproduct['customers_id'];
                                        $succe['quantity'] = $line_item['quantity'];
                                        $neworders['line_items'][] = $succe;
                                        //确定已经存到woo里
                                    } else {
                                        $url2 = $accounturl['shoplazaname']."/openapi/2020-07/products/".$line_item['product_id'];
                                        $data2 = $this->geturl_shoplaza($url2,$accounturl['shoplazatoken']);
                                        if($data2) {
                                            $data2 = json_decode($data2, true);
                                            if (!empty($data2['errors'])) {
                                                $row_p['customers_message'] = $data2['errors'][0];
                                            }
                                            if (!empty($data2['product'])) {
                                                $newproducts = array();
                                                $newproducts['name'] = $data2['product']['title'];
                                                if (isset($data2['product']['variants'][0]['price']) && !empty($data2['product']['variants'][0]['price'])) {
                                                    $newproducts['regular_price'] = $data2['product']['variants'][0]['price'];
                                                }else{
                                                    $newproducts['regular_price'] = 0;
                                                }
                                                $newproducts['description'] = $data2['product']['description'];
                                                //图片路径错误
//                                                $newproducts['images'] = array();
//                                                $newproducts['images'][]['src'] = $data2['product']['image']['src'];

                                                $url_products = 'https://ballclothe.com/wp-json/wc/v3/products';
                                                $return_products = $this->posturl_clicksend($url_products,$newproducts);
                                                $return_products = json_decode($return_products, true);
                                                if (!empty($return_products) && isset($return_products['id']) && !empty($return_products['id'])) {
                                                    $row_p['customers_status'] = 1;
                                                    $row_p['customers_id'] = $return_products['id'];
                                                    $succe['product_id'] = $return_products['id'];
                                                    $succe['quantity'] = $line_item['quantity'];
                                                    $neworders['line_items'][] = $succe;
                                                } else {
                                                    $row_p['customers_status'] = 2;
                                                    if (!empty($return_products['message'])) {
                                                        $row_p['customers_message'] = $return_products['message'];
                                                    }
                                                }
                                            }
                                        }
                                        $row_p['customers_time'] = time();
                                        Db::name('fedition_orderproductp')
                                            ->where('product_id', $line_item['product_id'])
                                            ->update($row_p);
                                    }
                                }
                            }
                        }

                        $neworders['payment_method'] = $data['order']['payment_method'];
                        //判读状态
                        $neworders['status'] = $this->neworders_status($data['order'],2);

                        $neworders['billing']['first_name'] = $data['order']['billing_address']['first_name'];
                        $neworders['billing']['last_name'] = $data['order']['billing_address']['last_name'];
                        $neworders['billing']['address_1'] = $data['order']['billing_address']['address1'];
                        $neworders['billing']['address_2'] = $data['order']['billing_address']['address2'];
                        $neworders['billing']['city'] = $data['order']['billing_address']['city'];
                        $neworders['billing']['country'] = $data['order']['billing_address']['country_code'];
                        if (!empty($data['order']['customer']['email'])) {
                            $neworders['billing']['email'] = $data['order']['customer']['email'];
                        }
                        $neworders['billing']['phone'] = str_replace(array("\r\n", "\r", " ", "\n"), "",$data['order']['shipping_address']['phone']);

                        $neworders['shipping']['first_name'] = $data['order']['shipping_address']['first_name'];
                        $neworders['shipping']['last_name'] = $data['order']['shipping_address']['last_name'];
                        $neworders['shipping']['address_1'] = $data['order']['shipping_address']['address1'];
                        $neworders['shipping']['address_2'] = $data['order']['shipping_address']['address2'];
                        $neworders['shipping']['city'] = $data['order']['shipping_address']['city'];
                        $neworders['shipping']['country'] = $data['order']['shipping_address']['country_code'];

                        $neworders['shipping_lines'][0]['method_id'] = 'flat_rate';
                        $neworders['shipping_lines'][0]['method_title'] = 'Flat Rate';
                        $neworders['shipping_lines'][0]['total'] = $data['order']['customer']['total_spent'];
                        $url = 'https://ballclothe.com/wp-json/wc/v3/orders';

                        $return_orders = $this->posturl_clicksend($url,$neworders);
                        $return_orders = json_decode($return_orders, true);

                        if (!empty($return_orders) && isset($return_orders['id']) && !empty($return_orders['id'])) {
                            $row['customers_status'] = 1;
                            $row['customers_id'] = $return_orders['id'];
                        } else {
                            $row['customers_status'] = 2;
                            if (!empty($return_orders['message'])) {
                                $row['customers_message'] = $return_orders['message'];
                            }
                        }
                    }
                }

                $row['customers_time'] = time();
                Db::name('fedition_ordershoplaza')
                    ->where('id', $t['id'])
                    ->update($row);
            }
        }
        return true;
    }

    public function neworders_status($order,$type)
    {
        if ($type == 1) {

        }
        if ($type == 2) {

        }

        //等待支付pending
        //处理中processing
        //搁置on-hold
        //已完成completed
        //取消cancelled
        //已退款refunded
        //失败failed
        $status = 'processing';
        return $status;
    }

    /**
     *5分钟更新一次订单
     * 订单信息 https://developer.myshoplaza.com/openapi/2020-07/orders
     * 商品详情 同上接口 line_item字段
     * 运单号详情 https://developer.myshoplaza.com/openapi/2020-07/orders/{order_id}/fulfillments
     * 商品附带SKU (先查商品详情-找到SKU列表-找到成本) https://developer.myshoplaza.com/openapi/2020-07/products/{product_id}
     */
    public function updateordertime($id = null)
    {

    }

    //计算电子邮件价格
    public function reports()
    {
        $url = 'https://ballclothe.com/wp-json/wc/v3/reports';
        $data = $this->geturl_clicksend($url);
        $data = json_decode($data, true);
        dump($data);
        die;
        return $data;
    }

    //商品详情
    public function orderinfo()
    {
        $iscustom = Db::name('fedition_accounturl')
            ->where('iscustom_woocommerce',1)
            ->where('status','normal')
//            ->where('id','39')
            ->find();
        $url = $iscustom['url']."/wp-json/wc/v3/orders/2764";
        $url = 'https://ballclothe.com/wp-json/wc/v3/orders/2764';
        $data = $this->geturl_clicksend($url);
        $data = json_decode($data, true);
        dump($data);
        die;
        return $data;
    }

    public function geturl_clicksend($url){
        $apikey = $this->apikey;
        $secretapikey = $this->secretapikey;
        $headerArray = array("Content-Type:application/json;",'Authorization:Basic '.base64_encode("$apikey:$secretapikey"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function posturl_clicksend($url,$data = array()){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $this->apikey;
        $secretapikey = $this->secretapikey;
        $headerArray = array("Content-Type:application/json;",'Authorization:Basic '.base64_encode("$apikey:$secretapikey"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    function geturl_shopify($url,$apikey,$secretapikey){
        $headerArray = array("Content-Type:application/json;",'Authorization:Basic '.base64_encode("$apikey:$secretapikey"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function geturl_shoplaza($url,$token){
        $headerArray = array("Content-Type: application/json;",'Access-Token: '.$token);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
